<template>
  <div class="login-container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login-form" :rules="rules" :model="loginForm" ref="ruleFormRef">
          <LocaleDropdown color="#fff" class="lang" />
          <h1>
            {{ t('login.welcome') }}
          </h1>
          <el-form-item prop="tenantId">
            <el-select v-model="loginForm.tenantId" :filterable="true" placeholder="请选择租户">
              <el-option
                v-for="(item, index) in tenantOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="userName">
            <el-input
              :prefix-icon="User"
              v-model="loginForm.userName"
              maxlength="32"
              :placeholder="t('login.usernamePlaceholder')"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              :prefix-icon="Lock"
              v-model="loginForm.password"
              maxlength="32"
              :placeholder="t('login.passwordPlaceholder')"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              class="login-btn"
              type="primary"
              size="default"
              @click="login(ruleFormRef)"
              :loading="isLoading"
            >
              {{ t('login.login') }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col></el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import LocaleDropdown from '@/components/localedropdown/src/index.vue';
import { User, Lock } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { LoginFormRequest } from '@/utils/api/user/type';
import type { FormInstance, FormRules } from 'element-plus';
import type { ValidateFieldsError, InternalRuleItem, Value } from 'async-validator/dist-types';
import { useI18n } from '@/hooks/web/useI18n';
const { t } = useI18n();
//引入用户相关的小仓库
import pinia from '@/stores';
import useUserStore from '@/stores/modules/user';
const defaultTenantId = '00000000-0000-0000-0000-000000000000';

const isLoading = ref<boolean>(false);
const loginForm = reactive<LoginFormRequest>({
  userName: 'admin',
  password: '1q2w3E*',
  tenantId: defaultTenantId
});
const ruleFormRef = ref<FormInstance>();
let useStore = useUserStore(pinia);
//获取路由器
let $router = useRouter();
//路由对象
let $route = useRoute();

interface Tenant {
  value: string;
  label: string;
}
// 租户参数 {为了方便调试先写死 可从租户表读取}
const tenantOptions = ref<Tenant[]>([
  {
    value: defaultTenantId,
    label: '宿主'
  },
  {
    value: '1cc37ea8-ea58-11ee-8c19-08bfb83e8436',
    label: '超级租户'
  }
]);

//自定义校验规则函数
const validatorUserName = (rule: InternalRuleItem, value: Value, callback: any) => {
  //rule:即为校验规则对象
  //value:即为表单元素文本内容
  //函数:如果符合条件callBack放行通过即为
  //如果不符合条件callBack方法,注入错误提示信息
  // if (value.length >= 5) {
  //   callback()
  // } else {
  //   callback(new Error('触发自定义验证'))
  // }

  callback();
};

// 校验规则
const rules = reactive<FormRules<LoginFormRequest>>({
  userName: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 32, message: '账号长度为3-32个字符', trigger: 'change' },
    { min: 3, max: 32, message: '账号长度为3-32个字符', trigger: 'blur' },
    { trigger: 'change', validator: validatorUserName }
  ],
  password: [
    { required: true, min: 3, max: 32, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 32, message: '密码长度为3-32个字符', trigger: 'change' },
    { min: 3, max: 32, message: '密码长度为3-32个字符', trigger: 'blur' }
  ],
  tenantId: [{ required: true, message: '请选择租户', trigger: 'change' }]
});

// 登录函数
const login = async (formEl: FormInstance | undefined): Promise<void> => {
  if (!formEl) {
    return;
  }

  // 提交验证
  await formEl.validate(
    async (isValid: boolean, invalidFields?: ValidateFieldsError): Promise<void> => {
      if (isValid) {
        // 执行登录逻辑
        try {
          isLoading.value = true;
          await useStore.userLogin(loginForm);
          let redirect: any = $route.query.redirect;
          $router.push({ path: redirect || '/' });
        } catch (error) {
          if (error) {
            let msg: string = (error as Error).message;
            if (msg) {
              ElMessage({
                showClose: true,
                message: (error as Error).message,
                type: 'error'
              });
            }
          }
        } finally {
          isLoading.value = false;
        }
      } else {
        console.log('error submit!', invalidFields);
      }
    }
  );
};
</script>
<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg');
  background-size: cover;

  .login-form {
    position: relative;
    width: 60%;
    top: 30vh;
    background: url('@/assets/images/login_form.png') no-repeat;
    background-size: cover;
    padding: 40px;

    .lang {
      position: absolute;
      top: 20px;
      right: 20px;
    }

    h1 {
      color: white;
      font-size: 40px;
    }

    h2 {
      font-size: 20px;
      color: white;
      margin: 20px 0px;
    }

    .login-btn {
      width: 100%;
    }
  }
}
</style>
